package com.banzhi.shop.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.banzhi.shop.R;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import static com.alipay.android.phone.mrpc.core.HttpManager.TAG;


/**
 * Created by admin on 2016/3/23.
 */
public class AndroidUtil {


    public static final int REQUEST_CODE_SELECT_HEAD = 0;
    public static final int REQUEST_CODE_CROP_HEAD = 1;
    public static final int REQUEST_CODE_SELECT_PICS = 6;


    public static String getJson(String fileName,Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

//    public static CustomProgress progressDialog;


//    /**
//     * 显示进度条
//     * @param context
//     */
//    public static void showDialog(Context context){
//        if(progressDialog!=null&&progressDialog.isShowing()){
//            return;
//        }
//        progressDialog=CustomProgress.show(context,"正在通信...");
//    }

//    /**
//     * 显示进度条
//     * @param context
//     */
//    public static void showDialog(Context context,String text){
//        progressDialog=CustomProgress.show(context, text);
//    }



//    public static void dismissDialog(Context context){
//        if(progressDialog!=null) {
//            progressDialog.dismiss();
//        }
//    }

    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }



    /**
     2  * 获取版本号
     3  * @return 当前应用的版本号
     4  */
     public static  String getVersion(Context context) {
             try {
                    PackageManager manager = context.getPackageManager();
                    PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
                    String version = info.versionName;
                    return version;
             } catch (Exception e) {
                    e.printStackTrace();
                    return "1";
                }
     }


    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    /**
     * 获取屏幕宽度
     * @param activity
     * @return
     */
    public final static int getWindowsWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }
    /**
     * 检测sdcard是否可用
     * @return true为可用，否则为不可用
     */
    public static boolean sdCardIsAvailable() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED))
            return false;
        return true;
    }

    /**
     * 检测SD卡是否有足够的空间
     * @param updateSize
     */
    public static boolean enoughSpaceOnSdCard(long updateSize) {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED))
            return false;
        return (updateSize < getRealSizeOnSdcard());
    }

    /**
     * 获取SD卡剩余空间大小
     */
    public static long getRealSizeOnSdcard() {
        File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 检测手机内存是否有足够的空间
     * @param updateSize
     */
    public static boolean enoughSpaceOnPhone(long updateSize) {
        return getRealSizeOnPhone() > updateSize;
    }

    /**
     * 获取手机内存
     */
    public static long getRealSizeOnPhone() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        long realSize = blockSize * availableBlocks;
        return realSize;
    }

    /**
     * 根据手机分辨率从dp转成px
     * @param context
     * @param dpValue
     * @return
     */
    public static  int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static  int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f)-15;
    }


    /**
     * 跳转界面
     * @param context
     * @param cls
     * @param mBundle
     */
    public static   void startActivity(Context context,Class<?> cls,Bundle mBundle)
    {
        Intent intent=new Intent();
        intent.setClass(context,cls);
        if (mBundle != null) {
            intent.putExtras(mBundle);
        }
        context.startActivity(intent);
    }


    /**
     * 有返回值的跳转
     *
     * @param context
     * @param cls
     * @param mBundle
     * @param resquestCode
     */
    public static void startActivityForResult(Context context,
                                              Activity activity, Class<?> cls, Bundle mBundle, int resquestCode) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        if (mBundle != null) {
            intent.putExtras(mBundle);
        }
        activity.startActivityForResult(intent, resquestCode);
    }




    /**
     * Toast提示
     * @param context
     * @param text
     */
    public static void showToast(Context context,String text){
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * Toast提示
     * @param context
     * @param textId
     */
    public static void showToast(Context context,int textId){
        Toast.makeText(context, textId, Toast.LENGTH_SHORT).show();
    }


    /**
     *
     * 获取下载图片保存路径
     * @date 2012-2-27
     * @return CrashHandler实例
     */
    public static  String getPicDownFilePath(Context ctx){
        String strFilePath = null;

        // 初始化默认路径
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        {
            strFilePath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/goddess/down/pics/";
        }
        // 如果没有SD卡，返回内存路径
        else
        {
            strFilePath = ctx.getFilesDir().getAbsolutePath() + "/goddess/down/pics/";
        }
        // 检查文件夹存不存在，如果不存在则创建
        File file = new File(strFilePath);
        if (!file.exists())
        {
            // 创建目录
            boolean result=file.mkdirs();
//            LogUtil.i("getPicDownFilePath", result + "");
        }

        return strFilePath;
    }




    /**
     * 强制隐藏输入法键盘
     */
    public static void hideInput(Context context,View view){
        InputMethodManager inputMethodManager =
                (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


//    public static ImageOptions getCommImageOption() {
//        ImageOptions imageOptions = new ImageOptions.Builder()
//                //.setImageScaleType(ImageView.ScaleType.FIT_XY)
//                .setPlaceholderScaleType(ImageView.ScaleType.FIT_XY)
//                .setLoadingDrawableId(R.drawable.default_icon)//加载中默认显示图片
//                .setFailureDrawableId(R.drawable.default_icon)//加载失败后默认显示图片
//                .build();
//        return imageOptions;
//    }
//
//    public static ImageOptions getCommHeadImageOption() {
//        ImageOptions imageOptions = new ImageOptions.Builder()
//                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
//                .setPlaceholderScaleType(ImageView.ScaleType.FIT_XY)
//                .setLoadingDrawableId(R.drawable.icon_user_default)//加载中默认显示图片
//                .setFailureDrawableId(R.drawable.icon_user_default)//加载失败后默认显示图片
//                .build();
//        return imageOptions;
//    }
//
//
//    public static ImageOptions getCommBannerImageOption() {
//        ImageOptions imageOptions = new ImageOptions.Builder()
//                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
//                .setPlaceholderScaleType(ImageView.ScaleType.FIT_XY)
//                .setLoadingDrawableId(R.drawable.default_icon)//加载中默认显示图片
//                .setFailureDrawableId(R.drawable.default_icon)//加载失败后默认显示图片
//                .build();
//        return imageOptions;
//    }
//
//    public static ImageOptions getCommShopBgImageOption() {
//        ImageOptions imageOptions = new ImageOptions.Builder()
//                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
//                .setPlaceholderScaleType(ImageView.ScaleType.FIT_XY)
//                .setLoadingDrawableId(R.drawable.shop_bg_one)//加载中默认显示图片
//                .setFailureDrawableId(R.drawable.shop_bg_one)//加载失败后默认显示图片
//                .build();
//        return imageOptions;
//    }
//
//
//
//    public static ImageOptions getImageOption(int loadImgId, int failImgId) {
//        ImageOptions imageOptions = new ImageOptions.Builder()
//                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
//                .setPlaceholderScaleType(ImageView.ScaleType.FIT_XY)
//                .setLoadingDrawableId(loadImgId)//加载中默认显示图片
//                .setFailureDrawableId(failImgId)//加载失败后默认显示图片
//                .build();
//        return imageOptions;
//    }


    public static String getLocalIpAddress()
    {
        try
        {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
            {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress())
                    {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
        catch (SocketException ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

//    public static String getWifiLocalIpAddress(Context context) {
//        WifiManager wifiManager = (WifiManager)context.getSystemService(Activity.WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        // 获取32位整型IP地址
//        int ipAddress = wifiInfo.getIpAddress();
//
//        //返回整型地址转换成“*.*.*.*”地址
//        return String.format("%d.%d.%d.%d",
//                (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
//                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
//    }


    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

//    public static  void showShare(final Context mContext, final Activity activity,final ShareBean shareBean){
//        List<String> items=new ArrayList<>();
//        items.add("微信好友");
//        items.add("复制链接");
//        items.add("二维码");
//        DialogFactory dialogFactory=DialogFactory.getInstance();
//        dialogFactory.showItemDialog(mContext,items);
//        dialogFactory.setmItemSelectedListener(new DialogFactory.OnDialogItemSelectedListener() {
//            @Override
//            public void onSelected(int which) {
//                switch (which){
//                    case 0:
//                        share(shareBean, SHARE_MEDIA.WEIXIN,activity,mContext);
//                        break;
//                    case 1:
//                        ClipboardManager myClipboard= (ClipboardManager)mContext.getSystemService(Context.CLIPBOARD_SERVICE);
//                        ClipData myClip;
//                        myClip = ClipData.newPlainText("text", shareBean.getTargetUrl());//text是内容
//                        myClipboard.setPrimaryClip(myClip);
//                        AndroidUtil.showToast(mContext,"已复制！");
//                        break;
//                    case 2:
//                        int hasWriteContactsPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                        if (hasWriteContactsPermission == PackageManager.PERMISSION_GRANTED) {
//                            Intent intent= new Intent(ContanstUtil.INTENT_ACTION_SHARE_CODE);
//                            intent.putExtra("sharebean",shareBean);
//                            mContext.sendBroadcast(intent);
//                        }else{
//                            AndroidUtil.showToast(mContext,"此功能需要开启读写SD卡权限！");
//                        }
//
//                        break;
//                }
//            }
//        });
////        new AlertDialog.Builder(mContext).setTitle("选择方式").setItems(new String[]{"微信好友","复制链接","二维码"}, new DialogInterface.OnClickListener() {
////            @Override
////            public void onClick(DialogInterface dialog, int which) {
////                dialog.dismiss();
////                MainEntity mMainInfo = SPUtils.getObjFromSp(mContext,SPUtils.KEY_MAIN);
////                switch (which){
////                    case 0:
////                        share(shareBean, SHARE_MEDIA.WEIXIN,activity,mContext);
////                        break;
////                    case 1:
////                        ClipboardManager myClipboard= (ClipboardManager)mContext.getSystemService(Context.CLIPBOARD_SERVICE);
////                        ClipData myClip;
////                        myClip = ClipData.newPlainText("text", shareBean.getTargetUrl());//text是内容
////                        myClipboard.setPrimaryClip(myClip);
////                        AndroidUtil.showToast(mContext,"已复制！");
////                        break;
////                    case 2:
////
////                        Intent intent= new Intent(ContanstUtil.INTENT_ACTION_SHARE_CODE);
////                        intent.putExtra("sharebean",shareBean);
////                        mContext.sendBroadcast(intent);
////                        break;
////                }
////
////            }
////        }).setNegativeButton("取消", null).show();
//    }
//
//    public static void share(ShareBean shareBean, SHARE_MEDIA share_media, Activity activity,final Context mContext){
//        ShareAction shareAction =   new ShareAction(activity) .setPlatform(share_media);
//        if(!StringUtils.isEmpty(shareBean.getContent())){
//            shareAction.withText(shareBean.getContent());
//        }
//        if(!StringUtils.isEmpty(shareBean.getTitle())){
//            shareAction.withTitle(shareBean.getTitle());
//        }
//        if(!StringUtils.isEmpty(shareBean.getShareImgUrl())){
//            shareAction.withMedia(new UMImage(mContext, shareBean.getShareImgUrl()));
//        }else if(shareBean.getDrawerId() != 0){
//            shareAction.withMedia(new UMImage(mContext,shareBean.getDrawerId()));
//        }
//        if(!StringUtils.isEmpty(shareBean.getTargetUrl())){
//            shareAction.withTargetUrl(shareBean.getTargetUrl());
//        }
//
//        shareAction.setCallback(new UMShareListener() {
//            @Override
//            public void onResult(SHARE_MEDIA platform) {
//                Toast.makeText(mContext," 分享成功啦", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onError(SHARE_MEDIA platform, Throwable t) {
//                Toast.makeText(mContext," 分享失败啦", Toast.LENGTH_SHORT).show();
//
//
//            }
//
//            @Override
//            public void onCancel(SHARE_MEDIA platform) {
//                Toast.makeText(mContext, " 分享取消了", Toast.LENGTH_SHORT).show();
//            }
//        }).share();
//    }

    public static String getFilePath(Context ctx,String pic) {
        String strFilePath = null;
        // 初始化默认路径
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            strFilePath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/"+pic+"/";
        }
        // 如果没有SD卡，返回内存路径
        else {
            strFilePath = ctx.getFilesDir().getAbsolutePath() + "/";
        }
        // 检查文件夹存不存在，如果不存在则创建
        File file = new File(strFilePath);
        if (!file.exists()) {
            // 创建目录
            file.mkdirs();
        }

        return strFilePath;
    }

    public static void notifyFileSystemChanged(Context context,String path) {
        if (path == null)
            return;
        final File f = new File(path);
        if (Build.VERSION.SDK_INT >= 19 ) { //添加此判断，判断SDK版本是不是4.4或者高于4.4
            String[] paths = new String[]{path};
            MediaScannerConnection.scanFile(context, paths, null, null);
        } else {
            final Intent intent;
            if (f.isDirectory()) {
                intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
                intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");
                intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
            } else {
                intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(Uri.fromFile(new File(path)));
            }
            context.sendBroadcast(intent);
        }
    }

    public static String  saveBitmapFile(Bitmap bitmap,String filePath){
        File file=new File(filePath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 图片上画文字
     *
     * @param bitmap
     * @param text  文字内容
     * @param textX  文字X坐标
     * @param textY  文字Y坐标
     * @return Bitmap
     */
    public static Bitmap drawTextAtBitmap(Bitmap bitmap, String text, float textX, float textY,Context context) {
        int x = bitmap.getWidth()+AndroidUtil.dip2px(context,50);
        int y = bitmap.getHeight()+AndroidUtil.dip2px(context,70);

        // 创建一个和原图同样大小的位图
        Bitmap newbit = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(newbit);
        canvas.drawColor(context.getResources().getColor(R.color.colorWhite));

        TextPaint paint = new TextPaint();

        // 在原始位置0，0插入原图
        canvas.drawBitmap(bitmap, AndroidUtil.dip2px(context,25), 0, paint);
        paint.setColor(context.getResources().getColor(R.color.blacktext));
        paint.setTextSize(AndroidUtil.dip2px(context,14));

        // 在原图指定位置写上字
       // canvas.drawText(text, textX, textY, paint);
        StaticLayout layout = new StaticLayout(text, paint,AndroidUtil.dip2px(context,230),Layout.Alignment.ALIGN_NORMAL,1.0F, 0.0F, true);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.translate(textX,textY);//从100，100开始画
        layout.draw(canvas);
        // 存储
        canvas.restore();

        return newbit;
    }

    /**
    计算ListView的高度，解决ScrollView和ListView两个View都有滚动的效果，在嵌套使用时起冲突的问题
    */
    public static void setListViewHeight(ListView listView) {

        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); //计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); //统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 生成视图的预览
     * @param activity
     * @param v
     * @return  视图生成失败返回null
     *          视图生成成功返回视图的绝对路径
     */
    public static String saveImage(Activity activity, View v) {
        Bitmap bitmap;
        String path =  Environment.getExternalStorageDirectory().getAbsolutePath()  + "preview.png";
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        bitmap = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        try {
            bitmap = Bitmap.createBitmap(bitmap, location[0], location[1], v.getWidth(), v.getHeight());
            FileOutputStream fout = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
            return path;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            LogUtils.d(TAG,"生成预览图失败"+e);
        } catch (IllegalArgumentException e) {
            LogUtils.d(TAG,"生成预览图失败是啊比了"+e);
        } finally {
            // 清理缓存
            view.destroyDrawingCache();
        }
        return null;

    }

    public static boolean isEmpty(String str) {
        return str == null || "".equals(str) || "null".equals(str.toLowerCase());
    }

    public static void copyText(Context context, String content) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newRawUri("copyLable", Uri.parse(content));
        cm.setPrimaryClip(mClipData);
    }
}
